import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex);
const store = new Vuex.Store({

    //保存商品列表数组
    state:{
        goodsList:[]
    },
    //给state里变量赋值
    mutations: {
        setGoodsList(state, newList) {
            state.goodsList=newList
        }
    },
    actions: {
        async asyncSetGoodsList(store) {
            const res = await axios({
                url: 'https://www.escook.cn/api/cart',
                method:'GET'
            })
            // 提交mutation修改state中的数据
            store.commit('setGoodsList',res.data.list)
        }
    },
    getters: {
        allCount(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count;
                }
                return sum
            },0)
        },
        allPrice(state) {
            return state.goodsList.reduce((sum, obj) => {
                if (obj.goods_state) {
                    sum += obj.goods_count*obj.goods_price;
                }
                return sum
            },0)
        },
    }

})
export default  store